package com.config.shiro;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.SerializationUtils;

import java.io.Serializable;
import java.util.Collection;

/**
 * 对 Session 进行操作
 * 带缓存：EnterpriseCacheSessionDAO
 */
@Slf4j
@RequiredArgsConstructor
public class RedisSessionDAO extends AbstractSessionDAO {
    final RedisTemplate redisTemplate;

    /**
     * 增加
     */
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);

        ValueOperations<Serializable, byte[]> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(sessionId, SerializationUtils.serialize(session));

        byte[] sessionBytes = valueOperations.get(sessionId);
        log.debug(Base64.encodeToString(sessionBytes));
        return sessionId;
    }

    /**
     * 读取
     */
    @Override
    protected Session doReadSession(Serializable sessionId) {
        ValueOperations<Serializable, byte[]> valueOperations = redisTemplate.opsForValue();
        byte[] sessionBytes = valueOperations.get(sessionId);
        if (sessionBytes == null) {
            return null;
        }
        return (Session) SerializationUtils.deserialize(sessionBytes);
    }

    /**
     * 更新
     */
    @Override
    public void update(Session session) throws UnknownSessionException {

    }

    /**
     * 删除
     */
    @Override
    public void delete(Session session) {

    }

    @Override
    public Collection<Session> getActiveSessions() {
        return null;
    }
}
